package com.dinghui.pay.controller.wxpay;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.dinghui.pay.common.ResponseResult;
import com.dinghui.pay.pojo.TbOrder;
import com.dinghui.pay.pojo.TbUser;
import com.dinghui.pay.pojo.param.PayOrderParam;
import com.dinghui.pay.pojo.param.SearchOrderStatusParam;
import com.dinghui.pay.pojo.param.UpdateNativeOrderStatusParam;
import com.dinghui.pay.service.OrderService;
import com.dinghui.pay.service.UserService;
import com.dinghui.pay.utils.JwtUtils;
import com.github.wxpay.sdk.MyWxPayConfig;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @author: trt
 * @description:
 * @create: 2021-06-05 19:46
 */
// 网站 微信业务接口
@RestController
@RequestMapping("/api/wx/web")
public class NativeController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private OrderService orderService;

    @Value("${wxpay.app-id}")
    private String appId;

    @Value("${wxpay.app-secret}")
    private String appSecret;

    @Value("${wxpay.key}")
    private String key;

    @Value("${wxpay.mch-id}")
    private String mchId;

    @Autowired
    private MyWxPayConfig myWXPayConfig;


    /**
     * 创建支付订单提交的参数
     * appid:公众号id
     * mch_id:商户号
     * nonce_str:随机字符串
     * sign:数字签名
     * body:商品描述
     * out_trade_no:商品订单号
     * total_fee:订单金额
     * spbill_create_ip:终端IP
     * notify_url:通知地址
     * trade_type:交易类型
     */

    /**
     * native付款
     */
    @PostMapping("/nativePayOrder")
    public ResponseResult nativePayOrder(@RequestBody PayOrderParam param, @RequestHeader HashMap header) {
        String token = header.get("token").toString();
        Long userId = Long.parseLong(jwtUtils.getClaimByToken(token).getSubject());
        int orderId = param.getOrderId();
        TbUser user = new TbUser();
        user.setUserId(userId);
        long count = userService.getCount(user);
        //判断用户是否存在
        if (count == 0) {
            return ResponseResult.error("用户不存在");
        }

        //判断用户是否拥有这个订单，并且订单是未支付状态
        TbOrder order = new TbOrder();
        order.setUserId(userId.intValue());
        order.setId(orderId);
        order.setStatus(1);
        count = orderService.getCount(order);
        if (count == 0) {
            return ResponseResult.error("不是有效的订单");
        }

        // todo 验证购物券是否有效
        // todo 验证团购活动是否有效

        //查询订单详情信息
        order = new TbOrder();
        order.setId(orderId);
        order = orderService.getOne(order); //订单对象
        //向微信平台发出请求，创建支付订单
        String amount = order.getAmount().multiply(new BigDecimal("100")).intValue() + "";

        try {
            WXPay wxPay = new WXPay(myWXPayConfig);
            HashMap map = new HashMap();
            map.put("nonce_str", WXPayUtil.generateNonceStr()); //随机字符串
            map.put("body", "订单备注");
            map.put("out_trade_no", order.getCode());
            map.put("total_fee", amount);
            map.put("spbill_create_ip", "127.0.0.1");
            map.put("notify_url", "https://127.0.0.1/test");
            map.put("trade_type", "NATIVE");
            String sign=WXPayUtil.generateSignature(map,key);
            map.put("sign",sign);
            Map<String, String> result = wxPay.unifiedOrder(map);
            String prepayId = result.get("prepay_id");
//            System.out.println(prepayId);
            String codeUrl=result.get("code_url");
            if (prepayId != null) {
                //更新本地商品订单信息，但是不更新商品订单状态
                order.setPrepayId(prepayId);
                order.setId(order.getId());  // 查询条件
                orderService.update(order);
                return ResponseResult.success("codeUrl", codeUrl);
            } else {
                return ResponseResult.error("支付订单创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("支付宝支付模块故障");
        }
    }

    // 生成支付二维码
    @GetMapping("/qrcode")
    public void qrcode(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String codeUrl=request.getParameter("codeUrl");
        if(codeUrl!=null&&codeUrl.length()>0){
            QrConfig qrConfig=new QrConfig();
            qrConfig.setWidth(250);
            qrConfig.setHeight(250);
            qrConfig.setMargin(2);
            OutputStream out=response.getOutputStream();
            QrCodeUtil.generate(codeUrl,qrConfig,"jpg",out);
            out.close();
        }
    }

    // 查询支付订单状态
    @PostMapping("/searchOrderStatus")
    public ResponseResult searchOrderStatus(@RequestBody SearchOrderStatusParam param, @RequestHeader HashMap header) {
        String token = header.get("token").toString();
        int userId = Integer.parseInt(jwtUtils.getClaimByToken(token).getSubject());
        int orderId = param.getOrderId();
        TbOrder order = new TbOrder();
        order.setUserId(userId);
        order.setId(orderId);
        int count = orderService.getCount(order);
        if (count == 0) {
            return ResponseResult.error("用户与订单不匹配");
        }
        order = orderService.getOne(order);
        String code = order.getCode();
        HashMap map = new HashMap();
        map.put("appid", appId);
        map.put("mch_id", mchId);
        map.put("out_trade_no", code);
        map.put("nonce_str", WXPayUtil.generateNonceStr());

        try {
            String sign = WXPayUtil.generateSignature(map, key);
            map.put("sign", sign);
            WXPay wxPay = new WXPay(myWXPayConfig);
            Map<String, String> result = wxPay.orderQuery(map);
            String returnCode = result.get("return_code");
            String resultCode = result.get("result_code");
            if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(resultCode)) {
                String tradeState = result.get("trade_state");
                if ("SUCCESS".equals(tradeState)) {
                    TbOrder tbOrder = new TbOrder();
                    tbOrder.setCode(code); // 查询条件
                    tbOrder.setStatus(2); // 修改值
                    tbOrder.setPaymentType(1);  // 修改值
                    orderService.updateOrderStatus(order);
                    return ResponseResult.success("订单状态已修改");
                } else {
                    return ResponseResult.success("订单状态未修改");
                }
            }
            return ResponseResult.success("订单状态未修改");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("查询支付订单失败");
        }
    }

}